﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using NetCore.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace NetCore
{
    public class PermissionAttribute : BasePermissionAttribute
    {
        public PermissionAttribute():base()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="code">权限标识（controller中请勿重复）</param>
        /// <param name="description">描述</param>
        public PermissionAttribute(string actionCode, string description) : base(actionCode, description)
        {
        }
      
        public override Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)
        {
            //匿名标识 无需验证
            if (filterContext.Filters.Any(e => (e as AllowAnonymousAttribute) != null))
                return Task.CompletedTask;
            if ((AppHttpContext.IsPost && !IsPost)||(!AppHttpContext.IsPost && !IsGet))
            {
                return Task.CompletedTask;
            }
            if (NoAccess)
            {
                WriteResult(filterContext, "该接口不允许访问");
                return Task.CompletedTask;
            }
            
            //if (!AppHttpContext.Current.User.Identity.IsAuthenticated)
            //{
            //    WriteResult(filterContext, "未登录，无权访问");
            //    return Task.CompletedTask;
            //}
            var userEntity = ApplicationEnvironments.DefaultSession.GetUser<UserEntity>();
            if (userEntity == null)
            {
                WriteResult(filterContext, "对不起，您无权访问");
                return Task.CompletedTask;
            }
            bool isAdminUser = userEntity.UserId.Equals(ApplicationEnvironments.Site.AdminUser);//判断是否系统管理员
            //获取请求的区域，控制器，action名称
            this.AreaName = string.IsNullOrWhiteSpace(this.AreaName) ? filterContext.RouteData.Values["area"]?.ToString() : this.AreaName;
            this.ControllerName = string.IsNullOrWhiteSpace(this.ControllerName) ? filterContext.RouteData.Values["controller"]?.ToString() : this.ControllerName;
            this.ActionName = string.IsNullOrWhiteSpace(this.ActionName) ? filterContext.RouteData.Values["action"]?.ToString() : this.ActionName;
            if (IsParent)
            {
                this.ActionName = "Index";
            }
            var isPermit = false;
            if (!string.IsNullOrWhiteSpace(ControllerName) && ControllerName.ToLower().Equals("home") && !string.IsNullOrWhiteSpace(ActionName) && ActionName.ToLower().Equals("index"))
            {
                ControllerName = "";
                ActionName = "";
            }
            else if (string.IsNullOrWhiteSpace(ActionName) || ActionName.ToLower().Equals("index"))
            {
                ActionName = "";
            }
            string routeUrl = "";
            routeUrl = (!string.IsNullOrWhiteSpace(AreaName) ? AreaName  : "").ToLower();
            if(!string.IsNullOrWhiteSpace(ControllerName))
            {
                routeUrl += "/" + ControllerName.ToLower();
            }
            if (!string.IsNullOrWhiteSpace(ActionName))
            {
                routeUrl += "/";
            }
            routeUrl += ActionName.ToLower();
            if (isAdminUser)
            {
                return Task.CompletedTask;
            }
            var isUmPermit = userEntity.UnPermission.Where(x => x.RouteUrl.ToLower().Equals(routeUrl)|| x.RouteUrl.ToLower().Equals(routeUrl+"/")).FirstOrDefault() != null;
            if (!isUmPermit)
            {
                isPermit = userEntity.Permission.Where(x => x.RouteUrl.ToLower().Equals(routeUrl) || x.RouteUrl.ToLower().Equals(routeUrl + "/")).FirstOrDefault() != null;
                if (isPermit)
                {
                    return Task.CompletedTask;
                }
            }

            WriteResult(filterContext, "对不起，您无权访问");
            return Task.CompletedTask;
        }
    }
}
